module Protobuf
  module Protoable
    def defined_filenames
      @defined_filenames ||= []
    end

    def defined_in(filename)
      defined_filenames << File.expand_path(filename)
    end

    def proto_filenames
      defined_filenames.map do |filename|
        retrieve_header(File.read(filename)).first
      end
    end

    def proto_contents
      #TODO: temporary implementation because the result includes not only this message but also all messages
      ret = {}
      defined_filenames.map do |filename|
        header = retrieve_header File.read(filename)
        ret[header.first] = header.last
      end
      ret
    end

    def retrieve_header(contents)
      if contents =~ /### Generated by rprotoc\. DO NOT EDIT!\n### <proto file: (.*)>\n((# .*\n)+)/
        proto_filename = $1
        proto_contents = $2.gsub(/^# /, '')
        [proto_filename, proto_contents]
      else
        [nil, nil]
      end
    end
  end
end
